import 'dart:convert';

import 'package:ecy_app_flutter/routes/goods/widgets/EcyGoodsSkuListView.dart';
import 'package:ecy_app_flutter/routes/goods/widgets/common/Debouncer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../EcyRouter.dart';
import '../../ecycommon/EcyCommonWidgets.dart';
import '../../ecycommon/EcyRequestBaseManager.dart';
import '../../model/EcyApiCommonResponse.dart';
import 'model/EcyGoodsSkuListModel.dart';

class EcyGoodsSearchPage extends EcyCommonBaseWidget {
  @override
  _EcyGoodsSearchPageState createState() {
    return _EcyGoodsSearchPageState(this);
  }
}

class _EcyGoodsSearchPageState extends EcyCommonBaseWidgetState {
  EcyGoodsSkuListModel skuListModel = EcyGoodsSkuListModel(0, 0, 0, 0, []);
  late EcyGoodsSkuListView skuListView;
  String searchKey = "";
  final Debounce debounce = Debounce();
  late EcyCommonBaseWidget controller;
  _EcyGoodsSearchPageState(EcyCommonBaseWidget vc) {
    controller = vc;
  }
  final TextEditingController _searchController = TextEditingController();

  int _currentPage = 1;
  bool _hasMore = false;
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();

    skuListView = EcyGoodsSkuListView(skuListModel, 0, (page) {
      requestSkuListData();
    });
  }

  //查询商品列表
  Future<bool> requestSkuListData() async {
    super.requestData();
    var response = await EcyRequestbasemanager().post(
        "/app/api/app/commodity/list", {
      "size": "10",
      "current": _currentPage,
      "name": searchKey,
      "status": 1
    });
    controller.dismissLoading();
    if (response != null) {
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        EcyGoodsSkuListModel currSkuListModel =
            EcyGoodsSkuListModel.fromJson(response["data"]);
        _hasMore = currSkuListModel.pages > _currentPage;
        _currentPage = currSkuListModel.current;
        setState(() {
          if (_currentPage == 1) {
            skuListModel = currSkuListModel;
          } else {
            skuListModel.records.addAll(currSkuListModel.records);
          }
        });
        skuListView.reloadData(skuListModel, _currentPage);
        if(skuListModel.records.isEmpty) {
          EasyLoading.showToast("没有找到$searchKey相关商品", duration: const Duration(seconds: 2), toastPosition: EasyLoadingToastPosition.center);
        }
      }
    }
    return true;
  }

  //下拉刷新
  Future<void> _onRefresh() async {
    _currentPage = 1;
    await requestSkuListData();
    _refreshController.refreshCompleted();
    // 重置上拉加载状态
    if (_hasMore) {
      _refreshController.loadComplete();
    } else {
      _refreshController.loadNoData();
    }
  }

  //上拉加载更多
  Future<void> _onLoading() async {
    if (_hasMore) {
      _currentPage++;
      await requestSkuListData();
      _refreshController.loadComplete();
    } else {
      _refreshController.loadNoData();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: const Color(0xFFFFFFFF),
        appBar: AppBar(
          automaticallyImplyLeading: false,
          scrolledUnderElevation: 0,
          titleSpacing: 0,
          title: Row(
            // alignment: WrapAlignment.spaceBetween,
            // direction: Axis.horizontal,
            spacing: 10.w,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                  // alignment: Alignment.center,
                  height: 36.w,
                  margin: EdgeInsets.only(left: 10.w),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(8.r)),
                    color: const Color(0x0A000000), //设置背景色为黑色
                  ),
                  width: MediaQuery.of(context).size.width - 60.w,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Padding(padding: EdgeInsets.only(left: 5.w)),
                      Image(
                          image: const AssetImage(
                              'assets/images/ic_home_search.png'),
                          width: 24.w,
                          height: 24.w),
                      // 左侧图标按钮
                      Expanded(
                        // 使TextField扩展剩余空间
                        child: Container(
                            alignment:Alignment.center ,
                            // margin: EdgeInsets.only(left: 4.w, bottom: 4.w),
                            height: 36.w,
                            child: TextField(
                              textAlignVertical: TextAlignVertical.center,
                              controller: _searchController,
                              autofocus: true,
                              decoration: InputDecoration(
                                isCollapsed: true,
                                // contentPadding: EdgeInsets.symmetric(vertical: 8.h),
                                hintText: "搜索",
                                hintStyle: TextStyle(
                                    fontSize: 16.sp,
                                    fontWeight: FontWeight.w300,
                                    color: const Color(0x73000000)),
                                border: InputBorder.none, // 移除默认边框，因为我们使用了Row布局
                              ),
                              onChanged: (String value) {
                                debounce.setDuration(
                                    const Duration(milliseconds: 300), () {
                                  setState(() {
                                    searchKey = value;
                                  });
                                  _onRefresh();
                                });
                              },
                            )),
                      ),
                      IconButton(
                          icon: const Icon(
                            Icons.clear,
                            size: 20,
                            color: Color(0x73000000),
                          ),
                          onPressed: () {
                            setState(() {
                              setState(() {
                                searchKey = "";
                              });
                              _searchController.text = "";
                              debounce.setDuration(
                                  const Duration(milliseconds: 300), () {
                                _onRefresh();
                              });
                            });
                          }), // 右侧图标按钮
                    ],
                  )),
              GestureDetector(
                  onTap: () {
                    EcyRouter.pop(context, "");
                  },
                  child: Text("取消",
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          fontWeight: FontWeight.w400,
                          fontSize: 16.sp,
                          color: const Color(0xD9000000)))),
            ],
          ),
          centerTitle: true,
          backgroundColor: Colors.white,
        ),
        body: SmartRefresher(
          enablePullDown: true,
          enablePullUp: true,
          physics: const AlwaysScrollableScrollPhysics(),
          header: const ClassicHeader(
            refreshStyle: RefreshStyle.Follow,
            idleText: '下拉刷新',
            refreshingText: '加载中...',
            completeText: '刷新完成',
            failedText: '刷新失败',
            textStyle: TextStyle(color: Color(0xFF8C8C8C), fontSize: 14),
            releaseText: '松开刷新',
            iconPos: IconPosition.top,
            spacing: 8,
          ),
          footer: CustomFooter(
            builder: (BuildContext context, LoadStatus? mode) {
              Widget body;
              if (mode == LoadStatus.idle) {
                body = const Text("上拉加载更多",
                    style: TextStyle(color: Color(0xFF8C8C8C)));
              } else if (mode == LoadStatus.loading) {
                body = const Text("加载中...",
                    style: TextStyle(color: Color(0xFF8C8C8C)));
              } else if (mode == LoadStatus.failed) {
                body = const Text("加载失败，点击重试",
                    style: TextStyle(color: Color(0xFF8C8C8C)));
              } else if (mode == LoadStatus.canLoading) {
                body = const Text("松手加载更多",
                    style: TextStyle(color: Color(0xFF8C8C8C)));
              } else {
                body = const Text("没有更多了~",
                    style: TextStyle(color: Color(0xFF8C8C8C)));
              }
              return SizedBox(
                height: 35.w,
                child: Center(child: body),
              );
            },
          ),
          onRefresh: () => _onRefresh(),
          onLoading: () => _onLoading(),
          controller: _refreshController,
          child: skuListView,
        ));
  }

  @override
  void dispose() {
    // 清理控制器，避免内存泄漏
    super.dispose();
    debounce.clear();
    _searchController.dispose();
    _refreshController.dispose();
  }
}
